# Patchless XMLRPC Service for Django
# Kind of hacky, and stolen from Crast on irc.freenode.net:#django
# Self documents as well, so if you call it from outside of an XML-RPC Client
# it tells you about itself and its methods
#
# Brendan W. McAdams <brendan.mcadams@thewintergrp.com>

# SimpleXMLRPCDispatcher lets us register xml-rpc calls w/o
# running a full XMLRPC Server.  It's up to us to dispatch data

from SimpleXMLRPCServer import SimpleXMLRPCDispatcher
from django.http import HttpResponse
from mysite.apps.blog.models import *

# Create a Dispatcher; this handles the calls and translates info to function maps
dispatcher = SimpleXMLRPCDispatcher()


def rpc_handler(request):
        """
        the actual handler:
        if you setup your urls.py properly, all calls to the xml-rpc service
        should be routed through here.
        If post data is defined, it assumes it's XML-RPC and tries to process as such
        Empty post assumes you're viewing from a browser and tells you about the service.
        """

        response = HttpResponse()
        if len(request.POST):
		#open("/tmp/123","w").write(request.raw_post_data)
                response.write(dispatcher._marshaled_dispatch(request.raw_post_data))
        else:
                response.write("<b>This is an XML-RPC Service.</b><br>")
                response.write("You need to invoke it using an XML-RPC Client!<br>")
                response.write("The following methods are available:<ul>")
                methods = dispatcher.system_listMethods()

                for method in methods:
                        # right now, my version of SimpleXMLRPCDispatcher always
                        # returns "signatures not supported"... :(
                        # but, in an ideal world it will tell users what args are expected
                        sig = dispatcher.system_methodSignature(method)

                        # this just reads your docblock, so fill it in!
                        help =  dispatcher.system_methodHelp(method)

                        response.write("<li><b>%s</b>: [%s] %s" % (method, sig, help))

                response.write("</ul>")
                response.write('<a href="http://www.djangoproject.com/"> <img src="http://media.djangoproject.com/img/badges/djangomade124x25_grey.gif" border="0" alt="Made with Django." title="Made with Django."></a>')

        response['Content-length'] = str(len(response.content))
        return response

def newPost(blogid, username, password, struct, publish):
    e=Entry()
    e.headline=struct["title"].encode("utf8")
    e.body=struct["description"].encode("utf8")
    e.save()
    return e.id

def getCategories(blogid, username, password):
    return [{"description":"BLOG","httpurl":"123","rssurl":"456"},]

def getRecentPosts(blogid, username, password, numberOfPosts):
    posts = []
    for e in Entry.objects.all()[:10]:
        posts.append({"link":"http://qingfeng.ushared.com"+e.get_absolute_url(),
	 "description":e.body,
	 "postid":e.id,
	 "title":e.headline,
	 "dateCreated":e.pub_date})
    return posts

def getPost(postid, username, password):
    e=Entry.objects.filter(id=postid)
    return {"link":"http://qingfeng.ushared.com"+e.get_absolute_url(),
	 "description":e.body,
	 "postid":e.id,
	 "title":e.headline,
	 "dateCreated":e.pub_date}

def editPost(postid, username, password, struct, publish):
    e=Entry.objects.filter(id=postid)
    if len(e)>0:
        e.headline=struct["title"].encode("utf8")
	e.body=struct["description"].encode("utf8")
	e.save()
    return True

def newMediaObject(blogid, username, password, struct):
    #open("/tmp/newMediaObject","w").write(str(username))
    raise "Method None"

def getUserInfo(appkey, username, password):
    return {"email":"paradise.qingfeng AT gmail.com","nickname":"QingFeng","url":"http://qingfeng.ushared.com/blog/"}

def getUsersBlogs(blogid,username,password):
    return [{"isAdmin":"1","url":"http://qingfeng.ushared.com/blog/","blogid":"1","blogName":"Qing Feng's Blog"},]

# you have to manually register all functions that are xml-rpc-able with the dispatcher
# the dispatcher then maps the args down.
# The first argument is the actual method, the second is what to call it from the XML-RPC side...
#dispatcher.register_function(multiply, 'multiply')
dispatcher.register_function(getUsersBlogs, 'blogger.getUsersBlogs')
dispatcher.register_function(getUserInfo, 'blogger.getUserInfo')
dispatcher.register_function(newPost, 'metaWeblog.newPost')
dispatcher.register_function(editPost, 'metaWeblog.editPost')
dispatcher.register_function(getCategories, 'metaWeblog.getCategories')
dispatcher.register_function(getRecentPosts, 'metaWeblog.getRecentPosts')
dispatcher.register_function(getPost, 'metaWeblog.getPost')
dispatcher.register_function(newMediaObject, 'metaWeblog.newMediaObject')
dispatcher.register_function(getUsersBlogs, 'metaWeblog.getUsersBlogs')
